package main

import (
	"encoding/json"
	"fmt"
	"go_final/mxshop_srvs/user_srv/config"
	"time"

	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

func main() {
	// 创建至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: "120.24.67.46",
			Port:   8848,
		},
	}

	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "d0ce3891-3f75-4215-aad6-e0f1d9e69913", // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		RotateTime:          "1h",
		MaxAge:              3,
		LogLevel:            "debug",
	}

	// 创建动态配置客户端
	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	if err != nil {
		panic(err)
	}

	// 获取配置：GetConfig
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: "user-srv",
		Group:  "dev"})

	if err != nil {
		panic(err)
	}

	fmt.Println("content", content)
	cfg := config.ServerConfig{}
	_ = json.Unmarshal([]byte(content), &cfg)
	fmt.Printf("cfg: %#v", cfg)

	// 监听配置变化：ListenConfig
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: "user-srv",
		Group:  "dev",
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("配置文件产生变化")
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})

	time.Sleep(300 * time.Second)
}
